package com.wx.tnsperson.controller;

import com.wx.tnsperson.response.FileService;
import com.wx.tnsperson.response.UploadFileResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:LLH
 * @Date:2020/7/25
 * @Description 文件上传下载
 */
@RequestMapping(value = "/file")
@RestController
@Api(tags = "文件上传下载")
public class FileController {

    private static final Logger logger= LoggerFactory.getLogger ( FileController.class );

    @Autowired
    private FileService fileService;


    @ApiOperation(value = "单文件上传", notes = "单文件上传")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public UploadFileResponse uploadFile( @RequestParam(value = "file",required = false) MultipartFile file ){
        String fileName=fileService.storeFile (file);

        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/downloadFile/")
                .path(fileName)
                .toUriString();

        return new UploadFileResponse(fileName, fileDownloadUri,
                file.getContentType(), file.getSize());

    }


    @ApiOperation(value = "多文件上传", notes = "多文件上传")
    @RequestMapping(value = "/uploadMultipleFiles", method = RequestMethod.POST)
    public List<UploadFileResponse> uploadMultipleFiles( @RequestParam(value = "files",required = false) MultipartFile[] files) {
        return Arrays.stream(files)
                .map(this::uploadFile)
                .collect( Collectors.toList());
    }

    @ApiOperation(value = "文件下载", notes = "文件下载")
    @RequestMapping(value = "/downloadFile/{fileName:.+}", method = RequestMethod.GET)
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
        // 加载资源文件
        Resource resource = fileService.loadFileAsResource(fileName);

        // 确定文件的内容类型
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("无法确定文件类型");
        }

        // 如果类型无法确定，是否不能回退到默认内容类型
        if(contentType == null) {
            contentType = "application/octet-stream";
        }


        return ResponseEntity.ok()
                .contentType( MediaType.parseMediaType(contentType))
                .header( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }


}
